function draw(){
    world.Step(1/60, 10, 10);
    context.fillStyle = '#cccccc';
    context.fillRect(0, 0, 500, 500);
    context.strokeRect(0, 0, 500, 500);

    // 绘制球的起点
    context.fillStyle = 'green';
    context.fillRect(ballOrgin.x - 100, ballOrgin.y - 20, 100, 40);

    for (var i = 0; i < boxs.length; i ++) {
        var position = boxs[i].GetPosition();
        var userData = boxs[i].GetUserData();
        context.save();
        context.setTransform(1, 0, 0, 1, 0, 0);
        context.translate(position.x * scaleFactor, position.y * scaleFactor);
        context.rotate(boxs[i].GetAngle());
        context.strokeStyle = 'green';
        context.strokeRect(0-(userData.width * scaleFactor/2) - 1, 0-(userData.height * scaleFactor/2) - 1, userData.width * scaleFactor, userData.height * scaleFactor);
        context.fillStyle = '#666666';
        context.fillRect(0-(userData.width * scaleFactor/2), 0-(userData.height * scaleFactor/2), userData.width * scaleFactor - 2, userData.height * scaleFactor - 2);
        context.restore();
    }
    for (var i = 0; i < balls.length; i++) {
        var position = balls[i].GetPosition();
        var fixtureList = balls[i].GetFixtureList();
        var shape = fixtureList.GetShape();
        context.beginPath();
        // 绘制小球
        context.strokeStyle = '#ff000';
        context.fillStyle = '#ff0000';
        context.arc(position.x * scaleFactor, position.y * scaleFactor, shape.GetRadius() * scaleFactor, 0, Math.PI * 2);
        context.fill();
        context.closePath();
    }
}

/**
 * 创建墙体
 * @constructor
 */
function CreateWall(){
    // 墙体
    wallDefs = [
        {
            x: canvas.width, y:0, w: canvas.width, h:1
        },
        {
            x: canvas.width, y:canvas.height, w:canvas.width, h:1
        },
        {
            x: 0, y:canvas.height, w:1, h:canvas.height
        },
        {
            x: canvas.width, y: canvas.height, w:1, h: canvas.height
        }

    ];
    for (var i = 0; i < wallDefs.length; i++) {
        // b2BodyDef 用来定义一个刚体
        var wallDef = new b2BodyDef;
        // 定义刚体的类型，staticbody为静态的，不会动的。
        wallDef.type = b2Body.b2_staticBody;
        // 定义位置
        wallDef.position.Set(wallDefs[i].x / scaleFactor, wallDefs[i].y /scaleFactor);
        var newWall = world.CreateBody(wallDef);
        // fixture定义刚体的形状
        var wallFixtrue = new b2FixtureDef;
        // 质量
        wallFixtrue.density = 10.0;
        // 阻力（0-1）
        wallFixtrue.friction = 1;
        // 弹性（0-1）
        wallFixtrue.restitution = 0.3;
        wallFixtrue.shape = new b2PolygonShape;
        wallFixtrue.shape.SetAsBox(wallDefs[i].w / scaleFactor, wallDefs[i].h / scaleFactor);
        newWall.CreateFixture(wallFixtrue);
        walls.push(newWall);
    }

}

/**
 * 创建箱子
 * @param boxWidth
 * @param boxHeight
 * @param number
 * @constructor
 */
function CreateBox(boxWidth, boxHeight, number){
    var startX = canvas.width - 100;
    var startY = canvas.height - boxHeight - 100;

    numBoxs = 10;
    for (var i = 0; i < number; i++) {
        var boxDef = new b2BodyDef;
        boxDef.type = b2Body.b2_dynamicBody;
        var ypos = (startY - (i*boxHeight)) / scaleFactor;
        var xpos = startX / scaleFactor;
        boxDef.position.Set(xpos, ypos);
        var newBox = world.CreateBody(boxDef);
        var boxFixture = new b2FixtureDef;
        boxFixture.density = 10.0;
        boxFixture.friction = 0.5;
        boxFixture.restitution = 0;
        boxFixture.shape = new b2PolygonShape;
        boxFixture.shape.SetAsBox((boxWidth/scaleFactor) / 2, (boxHeight/scaleFactor) / 2);
        newBox.CreateFixture(boxFixture);
        newBox.SetUserData({width: boxWidth / scaleFactor, height: boxHeight / scaleFactor});
        boxs.push(newBox);
    }
}

/**
 * 创建小球
 * @param event
 * @constructor
 */
function MouseUp(event){
    var x, y;
    if (event.pageX || event.pageY) {
        x = event.pageX;
        y = event.pageY;
    } else {
        x = event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
        y = event.clientY + document.body.scrollTop + document.documentElement.scrollTop;
    }
    x -= canvas.offsetLeft;
    y -= canvas.offsetTop;
    CreateBall(x, y);
}

/**
 * x和y为球的起点，沿着固定的速度飞行
 * @param x
 * @param y
 * @constructor
 */
function CreateBallFly(x, y){
    var ballDef = new b2BodyDef;
    ballDef.type = b2Body.b2_dynamicBody;
    var ypos = y /scaleFactor;
    var xpos = x / scaleFactor;
    var size = 7 / scaleFactor;
    ballDef.position.Set(xpos, ypos);
    var ballFixture = new b2FixtureDef;
    ballFixture.density = 10.0;
    ballFixture.friction = 0.6;
    ballFixture.restitution = 0.2;
    ballFixture.shape = new b2CircleShape(size);
    var newBall = world.CreateBody(ballDef);
    newBall.CreateFixture(ballFixture);
    var xVelocity = 30, yVelocity = 0;
    newBall.SetLinearVelocity(new b2Vec2(xVelocity, yVelocity));
    balls.push(newBall);

}

/**
 * x和y为球的方向，
 * @param x
 * @param y
 * @constructor
 */
function CreateBall(x, y){
    var ballDef = new b2BodyDef;
    ballDef.type = b2Body.b2_dynamicBody;
    var ypos = ballOrgin.x  /scaleFactor;
    var xpos = ballOrgin.y  / scaleFactor;
    var size = 7 / scaleFactor;
    ballDef.position.Set(xpos, ypos);
    var ballFixture = new b2FixtureDef;
    ballFixture.density = 10.0;
    ballFixture.friction = 0.6;
    ballFixture.restitution = 0.2;
    ballFixture.shape = new b2CircleShape(size);
    var newBall = world.CreateBody(ballDef);
    newBall.CreateFixture(ballFixture);
    // 根据x和y计算出角度
    var relativeX = x - ballOrgin.x;
    var relativeY = y - ballOrgin.y;
    var radian = Math.atan2(relativeY, relativeX);
    console.log('角度：', radian * 360 / (Math.PI * 2));

    console.log('x: ' + relativeX + ' y:' + relativeY);
    // 计算角度
    console.log(radian * 180 / Math.PI);
    // 限定初始速度为20；
    var xVelocity = 40 * ( Math.cos(radian));

    var yVelocity = 40 * (Math.sin(radian));
    newBall.SetLinearVelocity(new b2Vec2(xVelocity, yVelocity));
    balls.push(newBall);

}

var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');

// 定义box2dAPI
var b2Vec2 = Box2D.Common.Math.b2Vec2,
    b2BodyDef = Box2D.Dynamics.b2BodyDef,
    b2Body = Box2D.Dynamics.b2Body,
    b2FixtureDef = Box2D.Dynamics.b2FixtureDef,
    b2Word = Box2D.Dynamics.b2World,
    b2PolygonShape = Box2D.Collision.Shapes.b2PolygonShape,
    b2CircleShape = Box2D.Collision.Shapes.b2CircleShape,
    b2DebugDraw = Box2D.Dynamics.b2DebugDraw;
// 世界
var world = null;
// 定义球
var numBalls = null, balls = [];
// 墙体
var wallDefs = null, walls = [];
// canvas和box2d之间的转换比例
var scaleFactor = 30;

var numBoxs = null, boxs = [];

// 球的起点
var ballOrgin = null;


(function(){
    ballOrgin = {x: 100, y: 100}
    // 世界，b2V2c2里定义重力（x轴或y轴）
    world = new b2Word(new b2Vec2(0, 10), true);
    // 创建墙体
    CreateWall();
    // 创建箱子
    CreateBox(50, 50, 8);

    canvas.addEventListener("mouseup", MouseUp, false);


    window.setInterval("draw()", 10);
    // draw();
})();